import { Component, OnInit, TemplateRef } from '@angular/core';
import { ControlContainer, FormGroupDirective, FormGroup, FormControl } from '@angular/forms';
import { ZonePersonnel, ZoneService } from 'app/modules/zone/services/zone.service';
import { UserType } from 'app/modules/personnel/services/personnel.service';
import { MatDialog } from '@angular/material';
import { APIBase, ArrayAPIBase } from 'app/modules/base/api-base';
import { Router, ActivatedRoute } from '@angular/router';
import { PermissionConfig } from '../../services/permission.service';

@Component({
  selector: 'm-config',
  templateUrl: './config.component.html',
  styleUrls: ['./config.component.scss'],
})
export class ConfigComponent implements OnInit {
  admin_count: number; //管理员统计
  user_count: number; //普通用户统计
  pc_count: number; //终端统计
  pc_auth: boolean; //终端权限状态
  user_preview: APIBase<ZonePersonnel, ZonePersonnel>; // 已选人员预览
  pc_preview: APIBase<ZonePersonnel, ZonePersonnel>; //已选终端预览

  form = this.controlContainer.formDirective as FormGroupDirective;
  control: FormGroup;
  value = this.form.value as PermissionConfig;
  zoneID = Number(this.route.snapshot.queryParamMap.get('id'));
  defaultConfig = this.zoneService.getConfig(this.zoneID);

  constructor(
    public controlContainer: ControlContainer,
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private zoneService: ZoneService,
  ) {}
  inited = false;
  ngOnInit() {
    this.init();
  }

  async init() {
    if (this.value.user.all) {
      this.user_preview = this.zoneService.resource(this.zoneID, 'user');
    } else {
      this.user_preview = new ArrayAPIBase(this.value.user.selected);
    }
    this.admin_count = this.value.user.selected.filter(
      (p: ZonePersonnel) => p.utype === UserType.Admin,
    ).length;
    this.user_count = this.value.user.selected.length - this.admin_count;

    if (this.value.pc.all) {
      this.pc_preview = this.zoneService.resource(this.zoneID, 'pc');
    } else {
      this.pc_preview = new ArrayAPIBase(this.value.pc.selected);
    }
    this.pc_count = this.value.pc.selected.length;
    this.pc_auth = this.value.pc.auth;

    this.control = this.controlContainer.control as FormGroup;
  }

  async reset(name?: string) {
    const config = await this.defaultConfig;
    if (name) {
      this.control.controls[name].patchValue(config[name]);
    } else {
      this.control.patchValue(config);
    }
  }

  preview(templateRef: TemplateRef<any>) {
    this.dialog.open(templateRef);
  }
}
